package cn.otrue.patienthealthmanager.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetCheckUtil {
	/**未识别的其它网络*/
	public static final int NETWORK_TYPE_MOBILE_OTHER = 20;
	/**当前网络为WiFi*/
	public static final int NETWORK_TYPE_WIFI = 1;
	/**当前网络为手机网络*/
	public static final int NETWORK_TYPE_MOBILE_2G = 21;
	public static final int NETWORK_TYPE_MOBILE_3G = 22;
	public static final int NETWORK_TYPE_MOBILE_4G = 23;
	/**无网络连接*/
	public static final int NETWORK_TYPE_MOBILE_NONE = -1;

	/**
	 * 判断当前手机是否连网
	 * @param context
	 * @return 
	 */
	public static boolean checkNet(Context context) {

		int netType = getNetType(context);
		if (netType != NETWORK_TYPE_MOBILE_NONE) {
			return true;
		}
		return false;
	}

	/**
	 * 获取当前手机连接的网络类型
	 * 
	 * @param context
	 * @return
	 */
	public static int getNetType(Context context) {
		ConnectivityManager connectMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connectMgr.getActiveNetworkInfo();
		if (info != null && info.isConnectedOrConnecting()) {
			switch (info.getType()) {
			case ConnectivityManager.TYPE_MOBILE:
				switch (info.getSubtype()) {
				case 1:
				case 2:
				case 4:
					return NETWORK_TYPE_MOBILE_2G;
				case 13:
					return NETWORK_TYPE_MOBILE_4G;
				case 5:
				case 6:
				case 12:
				case 8:
				case 3:
				case 9:
				case 15:
					return NETWORK_TYPE_MOBILE_3G;
				default:
					return NETWORK_TYPE_MOBILE_OTHER;
				}
			case ConnectivityManager.TYPE_WIFI:
				return NETWORK_TYPE_WIFI;
			default:
				return NETWORK_TYPE_MOBILE_OTHER;
			}
		} else {
			return NETWORK_TYPE_MOBILE_NONE;// 当前无网络连接，返回-1
		}
	}
}
